<template>
	<view class="contont">
		<nav-bar :title="pageInfo.navbarTitle" :iconLeft="true" />
		<uni-forms :model="form" :rules="rules" ref="refForm" labelAlign="right" label-width="90px">
			<view class="content-bgc">
				<view class="b-con">
					<uni-forms-item label="采购入库单号" name="code" required>
						<view style="display: flex;gap:20rpx">
							<uni-easyinput v-model="form.code" placeholder="请输入采购入库单号" class="iptBor" :inputBorder="false"
								:disabled="switchCode" />
							<view style="margin-left: 20rpx" v-show="pageInfo.type == 'add'">
								<u-switch v-model="switchCode" @change="switchChange" size="20" />
								自动生成
							</view>
						</view>
					</uni-forms-item>
					<uni-forms-item label="采购单号" name="purchase_order" required>
						<uni-data-select mode="underline" placeholder="请选择采购单号" v-model="form.purchase_order"
							:localdata="order_list" :clear="true" :disabled="pageInfo.type == 'edit'" @change="order_change" />
					</uni-forms-item>
					<uni-forms-item label="采购数量" v-show="form.purchase_order != null">
						<uni-easyinput v-model="mar_or.order_num" class="iptBor" :inputBorder="false" :disabled="true" />
					</uni-forms-item>
					<uni-forms-item label="下单日期" v-show="form.purchase_order != null">
						<uni-easyinput v-model="mar_or.order_date" class="iptBor" :inputBorder="false" :disabled="true" />
					</uni-forms-item>
					<uni-forms-item label="入库日期" name="in_date" required>
						<view class="dateTimeBottom">
							<uni-datetime-picker type="datetime" placeholder="入库日期" :clear-icon="false" v-model="form.in_date"
								@show="car_popup_Show = false" @maskClick="car_popup_Show = true" @change="car_popup_Show = true"
								:border="false" />
						</view>
					</uni-forms-item>
					<uni-forms-item label="备注" name="desc">
						<uni-easyinput type="textarea" v-model="form.desc" placeholder="请输入备注" />
					</uni-forms-item>
				</view>
			</view>
			<view class="car-jiesuan" @click="car_popupShow = !car_popupShow" v-show="car_popup_Show">
				<view class="fotter-icon">
					<image class="cartIcon" src="@/static/adjust_icon_01.png"></image>
				</view>
				<view class="fotter-texts">
					<u--text type="info" :text="`产品数量：${form.bom_list.length}`"></u--text>
				</view>
				<view class="fotter-btn" :class="{ btnBgc: Boolean(form.bom_list.length) }" v-show="car_popupShow"
					@click.stop="save">提交</view>
				<view style="margin-left: auto;" v-show="!car_popupShow"><u--text text="点击查看" type="primary" suffixIcon="eye"
						iconStyle="font-size: 40rpx;color:#3c9cff" /></view>
			</view>
			<custom-popup :popupShow="car_popupShow" mode="bottom" title="发货产品" class="car-popup-custom"
				@close="car_popupShow = false" height="70vh">
				<z-paging v-if="car_popupShow" ref="paging_car" :refresher-enabled="false" :loading-more-enabled="false" :fixed="false"
					v-model="form.bom_list" @query="queryList_car">
					<view slot="top" class="zpagin_top">
						<view class="search">
							<view class="hint-text">当前入库量应在 0 和 (采购数量 - 已入库量) 之间</view>
						</view>
					</view>
					<uni-card v-for="(item, index) in form.bom_list" :key="index" :title="item.name" :sub-title="item.code"
						margin="5px" spacing="0">
						<view class="swipe-action">
							<view class="text-2">规格：{{ item.specification }}</view>
							<view class="con">
								<view class="ctent">供应商：{{ item.supplier_name }}</view>
								<view class="ctent">采购价(元)：{{ item.supplier_price }}</view>
							</view>
							<view class="con">
								<view class="ctent">采购数量：{{ item.num }}</view>
								<view class="ctent">采购单位：{{ item.in_unit }}</view>
							</view>
							<view class="con">
								<view class="ctent">总金额：{{ item.total_price }}</view>
								<view class="ctent">已入库量：{{ item.finish_num }}</view>
							</view>
							<uni-forms-item label="存放仓库：" :name="`bom_list[${index}].warehouse`" required
								:rules="[{ required: true, errorMessage: `请选择【${item.name}】的存放仓库` }]">
								<uni-data-select mode="underline" placeholder="请选择存放仓库" v-model="item.warehouse"
									:localdata="warehouse_list" :clear="false" placement="top" />
							</uni-forms-item>
							<view class="con">
								<view class="ctentdate_text" style="flex: none;">当前入库量：</view>
								<custom-num-box v-model="item.now_num" :min="0" @change="change_num($event, item)" :asyncChange="true"
									:decimal-length="2"></custom-num-box>
							</view>
							<view class="con">
								<view class="ctent">入库总金额：{{ item.now_price }}</view>
								<view class="ctent">优惠率（%）：{{ item.discount }}</view>
							</view>
						</view>
					</uni-card>
					<view slot="bottom">
						<view class="zhanwei"></view>
					</view>
				</z-paging>
			</custom-popup>
		</uni-forms>
	</view>
</template>
<script setup>
import { reactive, ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app'
import puInApi from '../../../api/purchase/pu_in'
import { generateCode, debounce } from '@/utils/index.js';
import Decimal from 'decimal.js-light';

//页面标题
const pageInfo = reactive({
	navbarTitle: '采购入库',
	type: '',
	edit_id: null,
});

onLoad(option => {
	get_warehouse_list()
	get_purchase_order_list()
	pageInfo.type = option.type
	if (option.type == 'edit') {
		pageInfo.navbarTitle = pageInfo.navbarTitle + '(修改)'
		get_detail(option.id)
		pageInfo.edit_id = option.id
	} else {
		pageInfo.navbarTitle = pageInfo.navbarTitle + '(新增)'
		form.code = generateCode('IN')
	}
})

//自动生成按钮
const switchCode = ref(true);
function switchChange(v) {
	if (v) {
		form.code = generateCode('IN')
	}
}

const refForm = ref(null)
const form = reactive({
	code: '',
	purchase_order: null,
	in_date: '',
	desc: '',
	bom_list: []
})
const fields = Object.keys(form);

const mar_or = reactive({
	order_num: '',
	order_date: '',
})
const rules = {
	code: { rules: [{ required: true, errorMessage: '请输入采购入库单号' }] },
	in_date: { rules: [{ required: true, type: 'number', errorMessage: '请选择入库日期' }] },
	purchase_order: { rules: [{ required: true, errorMessage: '请选择采购单' }] },
}
function get_detail(id) {
	puInApi.purchase_in_detail(id).then(res => {
		const record = uni.$lodash.pick(res, fields)
		Object.assign(form, record)
		puInApi.purchase_order_detail(res.purchase_order).then(res => {
			mar_or.order_date = res.order_date
			mar_or.order_num = res.order_num
		})
		form.bom_list = res.purchase_in_order_boms.map(v => {
			return {
				id: v.bom.id,
				code: v.bom.code,
				name: v.bom.name,
				specification: v.bom.specification,
				supplier_id: v.supplier_id,
				supplier_name: v.supplier_name,
				supplier_price: v.supplier_price,
				discount: parseFloat(v.discount),
				total_price: v.total_price,
				now_price: v.now_price,
				num: v.purchase_num,
				finish_num: v.finish_num,
				in_unit: v.in_unit,
				warehouse: v.warehouse,
				now_num: v.now_num
			}
		})
	})
}

function order_change(v) {
	form.bom_list = []
	if (!v) {
		form.purchase_order = null
		return
	}
	puInApi.purchase_order_detail(v).then(res => {
		mar_or.order_date = res.order_date
		mar_or.order_num = res.order_num
		form.bom_list = res.purchase_order_boms.map(v => {
			return {
				id: v.bom.id,
				code: v.bom.code,
				name: v.bom.name,
				specification: v.bom.specification,
				cost: v.cost,
				all_cost: v.bom.all_cost,
				main_price: v.main_price,
				num: v.num,
				discount: parseFloat(v.discount),
				total_price: v.total_price,
				finish_num: v.finish_num,
				in_unit: v.unit,
				warehouse: null,
				now_num: 0,
				supplier_name: v.supplier_name,
				supplier_price: v.supplier_price,
				supplier_id: v.supplier_id
			}
		})
	})
}

function change_num(e, row) {
	if (!row.warehouse) {
		return uni.$u.toast('请选择存放仓库')
	}
	if (e.value > row.num - row.finish_num) {
		row.now_num = row.num - row.finish_num
		return uni.$u.toast('当前入库量应在 0 和 (采购数量 - 已入库量) 之间')
	}
	row.now_num = e.value
	const all = new Decimal(row.supplier_price).mul(new Decimal(row.now_num || 0))
	const discount = new Decimal(row.discount || 0)
	const now_price = all.sub(all.mul(discount).div(100))
	row.now_price = now_price.toDecimalPlaces(2).toNumber()
}

const car_popupShow = ref(false)
const car_popup_Show = ref(true)
const paging_car = ref(null)
function queryList_car() {
	paging_car.value.complete(form.bom_list);
}

const warehouse_list = ref([])
function get_warehouse_list() {
	const params = { page: 1, page_size: 99999 }
	puInApi.get_warehouse(params).then(res => {
		warehouse_list.value = res.results.map(v => ({
			text: v.name,
			value: v.id
		}))
	})
}

const order_list = ref([])
function get_purchase_order_list() {
	const params = { page: 1, page_size: 99999, status: '2,3' }
	puInApi.get_purchase_order(params).then(res => {
		order_list.value = res.results.map(v => ({
			text: v.code,
			value: v.id
		}))
	})
}
function save() {
	refForm.value.validate().then(() => {
		const params = uni.$lodash.cloneDeep(form) // 深拷贝一份form表单
		if (pageInfo.type == 'add') {
			puInApi.post_purchase_in(params).then(res => {
				uni.$u.toast('添加成功')
				setTimeout(() => {
					backRefsh();
				}, 1000)
			})
		} else {
			//修改
			puInApi.patch_purchase_in(params, pageInfo.edit_id).then((res) => {
				uni.$u.toast('修改成功')
				setTimeout(() => {
					backRefsh();
				}, 1000)
			})
		}

	}).catch((error) => {
		uni.$u.toast(error[0].errorMessage);
	})
}

//返回上一级并刷新上一级页面
function backRefsh() {
	uni.navigateBack({
		delta: 1, // 返回的页面层数，1 表示返回上一级
		success: () => {
			uni.$bus.useBusEmit('pu_in:refresh')
		}
	})
}
</script>

<style lang="scss" scoped>
.date_text {
	width: 90px !important;
}
</style>